package patrol.mobile.com.mobilepatrol.persenter;

import android.util.Log;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import io.realm.Realm;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.User;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.view.UserView;

/**
 * Created by apple on 17/9/27.
 */

public class UserPer {
    private UserView mView;

    public UserPer(UserView mView) {
        this.mView = mView;
    }

    public void getUsers() {
        OkHttpUtils
                .get()
                .url(SPUtils.get(Constants.current_ser, "") + Urls.getUsers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mView.hideLoading();
                        mView.onUserError(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        SPUtils.put(SPUtils.USER_DATA, response);
                        UserManager.delUsers();
                        try {
                            JSONObject object = new JSONObject(response);
                            if (object.getInt("state") == 200) {
                                final JSONArray array = object.getJSONArray("yhList");
                                PatrolApp.realm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        realm.createAllFromJson(User.class, array.toString());
                                    }
                                });
                                mView.hideLoading();
                                mView.onUserSuccess("初始化用户成功");
                            } else {
                                mView.onUserError("初始化用户失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                });
    }
}
